package com.wise.service.cms.content.uploadresource;

import com.wise.entities.content.Resource;
import com.wise.entities.content.ResourceGroup;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daomodel.DaoList;
import com.wise.framework.validation.Precondition;
import com.wise.summer.v1.cms.content.uploadresources.ListUploadResourcesByGroupName;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.util.List;

import static com.wise.model.content.ContentErrMsgs.Err_100100000004;

@Service
@SummerService
public class ListUploadResourcesByGroupNameService implements SummerServiceBean<ListUploadResourcesByGroupName> {
    @Value("${azure.file.url}")
    private String url;

    @Override
    public void sum(ListUploadResourcesByGroupName summer) {
        SqlSelect select = SqlSelect.selec("*")
                .fromClassName(Resource.class, "res")
                .left_outer_join("upload_resource_groups gr on res.group_id=gr.id")
                .eq(ResourceGroup._groupName, summer.getGroupName())
                .order_by(Resource.UPLOAD_TIME + " desc");

        List<Resource> list = DaoList.s(Resource.class, select);
        Precondition.checkNotNull(list, Err_100100000004);
        if (StringUtils.isNotEmpty(url)) {
            for (Resource resource : list) {
                int index = resource.getPath().lastIndexOf("/");
                String fileName = resource.getPath().substring(index + 1);
                resource.setPath(url + fileName);
                resource.setResourcePath(url + fileName);
            }
        }
        summer.setSummerResult(list);
    }
}
